import React from 'react'
import ReactDOM from 'react-dom'
import debounce from "lodash.debounce";
import { connect } from 'react-redux';
import {EventUtils, messages} from 'share/common';
import SingleMainGuide from 'components/template/main-init-modal-manage/mask-guide/single-main-guide';
import wrapGuide from 'components/method/wrapGuide';
/**
 *
 * 参照 的 full-screen
 *
 */
class MaskGuide extends React.Component{
  constructor(props) {
    super(props);
    this.container = null;
    this.state = {
      innerWidth: 0,
      innerHeight: 0,
      maskList: [],
      currentIndex: 0
    }
    this.List = [
      {
        elementId: 'helios-content-guide-id',
        transparentArea: undefined,
        mouseOverId: undefined
      },
      {
        elementId: 'menu-container-guide-id',
        transparentArea: undefined,
        mouseOverId: undefined
      },
      {
        elementId: 'messages-center-icon-guide-id',
        transparentArea: undefined,
        mouseOverId: undefined
      },
      {
        elementId: 'help-icon-popover-guide-id',
        transparentArea: undefined,
        mouseOverId: 'help-content-guide-id'
      },
      {
        elementId: 'user-info-dropdown-guide-id',
        transparentArea: undefined,
        mouseOverId: 'user-info-header-list-guide-id'
      },
      {
        elementId: 'menu-header-container-guide-id',
        transparentArea: undefined,
        mouseOverId: undefined
      }
    ];
    this.options = [{
      ref: document.getElementById("helios-content-guide-id"),
      title: messages('common-1.key403')/*首页*/,
      content: messages('common-1.key404')/*普通员工有个人首页，可以看到与自己相关费用的使用、报销、统计信息；超级管理员可以切换至 管理员首页，了解租户下各项服务的使用情况*/,
      placement: "main",
      block: 'start',
      arrowStyle: {
        top: '-35px'
      }
    }, {
      ref: document.getElementById("menu-container-guide-id"),
      title: messages('common-1.key405')/*菜单导航*/,
      content: messages('common-1.key406')/*在这里可以查找需要的功能，比如发起 申请单、报销单、借款单，配置工作流等；也可以通过大类搜索想要的功能，也可以直接搜索菜单名称*/,
      placement: "right",
      block: "start",
      arrowStyle: {
        left: '-54px'
      }
    },{
      ref: document.getElementById("messages-center-icon-guide-id"),
      title: messages('common-1.key407')/*个人消息中心*/,
      content: messages('common-1.key408')/*在这里可以查看、处理收到的消息通知、待办信息*/,
      placement: "bottom",
      inline: "end",
      dynamic: true,
      arrowStyle: {
        left: '323px',
        top: '-29px'
      }
    },{
      ref: document.getElementById("help-icon-popover-guide-id"),
      title: messages('common-1.key409')/*帮助与反馈*/,
      content: messages('common-1.key410')/*在这里可以看到产品手册和常见问题解答，及时获取到最新的产品信息，也可以在线联系客服人员获取帮助*/,
      placement: "help",
      inline: "end",
      dynamic: true,
      arrowStyle: {
        left: '412px',
        top: '-29px'
      }
    },{
      ref: document.getElementById("user-info-dropdown-guide-id"),
      title: messages('common-1.key411')/*个人设置*/,
      content: messages('common-1.key412')/*在这里你可以查看和修改与自己相关的个人信息*/,
      placement: "mine",
      block: "end",
      arrowStyle: {
        left: '384px',
        top: '-20px'
      }
    },{
      ref: document.getElementById("menu-header-container-guide-id"),
      title: messages('common-1.key413')/*所在租户名称*/,
      content: messages('common-1.key414')/*点击这里，不论你在哪里，都可以直接返回首页*/,
      placement: "right",
      block: "end",
      arrowStyle: {
        left: '-36px',
        top: '-18px'
      }
    }];
    this.resizeInit = debounce(this.resizeInit, 300)
  }

  /*
  * 1.主体内容页面 helios-content-guide-id               高亮
  * 2.菜单        menu-container-guide-id               高亮
  * 3.消息中心     messages-center-icon-guide-id        高亮
  *
  * 4.帮助 help-icon-popover-guide-id        hover  高亮
  *   帮助list     help-content-guide-id                高亮
  *
  * 5.头像 id     user-info-dropdown-guide-id    hover  高亮
  *   个人设置退出 area user-info-header-list-guide-id   高亮
  *
  * 6.公司名区域   menu-header-container-guide-id        高亮
  *
  * */

  initGuideList = () => {
    let list = [];
    const { loginUser, menuTree } = this.props;
    this.List.forEach((item, index)=>{
      let single = {elementId: item.elementId, transparentArea: undefined, mouseOverId: item.mouseOverId, hoverTransparent: undefined}
      let el = document.getElementById(item.elementId);
      if (el !== null) {
        single.transparentArea = this.getElPosition(el);
        //处理特殊情况  首页（只要半屏） 菜单（右边多了个宽） 消息图标，帮助图标（要等比 大点）
        if (single.elementId === 'helios-content-guide-id')  {
          single.transparentArea.height = 500;  //固定500
        } else if (single.elementId === 'menu-container-guide-id') {
          single.transparentArea.width = 200;  //固定200
        } else if (single.elementId === 'messages-center-icon-guide-id' || single.elementId === 'help-icon-popover-guide-id') {
          single.transparentArea.x-=6;
          single.transparentArea.y-=6;
          single.transparentArea.width = 28;  //固定28
          single.transparentArea.height = 28;  //固定28
        }
        if (single.elementId === 'user-info-dropdown-guide-id') {
          if (!loginUser.mock && menuTree.allAPIMenuItem["personal-settings"]) {
            list.push(Object.assign(single, this.options[index]));
          }
        } else {
          list.push(Object.assign(single, this.options[index]));
        }
      }
    })
    this.setState({maskList: list})
  }

  triggerANode = (elementID, isEnter) => {
    if (isEnter) {
      let mouseOverEvent = document.createEvent('HTMLEvents');
      mouseOverEvent.initEvent('mouseover', true, true);
      document.getElementById(elementID) && document.getElementById(elementID).dispatchEvent(mouseOverEvent);
    } else {
      let mouseLeaveEvent = document.createEvent('HTMLEvents');
      mouseLeaveEvent.initEvent('mouseout', true, true);
      document.getElementById(elementID) && document.getElementById(elementID).dispatchEvent(mouseLeaveEvent);
    }
  }

  getElPosition = (el) => {
    let pos = {x: 0, y: 0, width: 0, height: 0};
    pos.width = el.clientWidth;
    pos.height = el.clientHeight;

    let offsetEl = el, scrollEl = el;

    while (offsetEl !== document.body && offsetEl) {
      pos.x += offsetEl.offsetLeft;
      pos.y += offsetEl.offsetTop;
      offsetEl = offsetEl.offsetParent;
    }

    while (scrollEl !== document.body && scrollEl) {
      pos.x -= scrollEl.scrollLeft;
      pos.y -= scrollEl.scrollTop;
      scrollEl = scrollEl.parentNode;
    }
    pos.x += document.body.clientLeft - document.body.scrollLeft;
    pos.y += document.body.clientTop - document.body.scrollTop;
    return pos;
  };

  ctxDelegate = (method, ...params) => {
    let curParams = params.map(param => {
      if (typeof(param) === 'number') {
        return param * window.devicePixelRatio
      } else {
        return param
      }
    })
    this.ctx[method](...curParams)
  }

  getLatestWindowSize = () => {
    let innerWidth = 0;
    let innerHeight = 0;
    if (window.innerWidth)
      innerWidth = window.innerWidth;
    else if ((document.body) && (document.body.clientWidth))
      innerWidth = document.body.clientWidth;
    if (window.innerHeight)
      innerHeight = window.innerHeight;
    else if ((document.body) && (document.body.clientHeight))
      innerHeight = document.body.clientHeight;
    return {innerWidth, innerHeight}
  }

  initMask = () => {
    let {innerWidth, innerHeight} = this.getLatestWindowSize();
    this.setState({innerWidth, innerHeight}, ()=>{
      this.container = document.createElement('div');
      this.container.style.position = 'fixed';
      this.container.style.top = 0;
      this.container.style.right = 0;
      this.container.style.left = 0;
      this.container.style.bottom = 0;
      this.container.style.zIndex = 9999;
      document.body.append(this.container);
      this.renderChildren(this.props);
      this.CanvasRef = document.getElementById('mask-guide-canvas')
      if (!this.ctx) {
        this.ctx = this.CanvasRef.getContext('2d');
      }
      this.drawBackground();
      if (this.List.length) {
        this.drawCurrentGuide()
      }
    })
  }

  drawBackground = (newInnerWidth, newInnerHeight) => {
    let {ctx, ctxDelegate} = this;
    const { innerWidth, innerHeight } = this.state;
    ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
    ctxDelegate('fillRect', 0, 0, newInnerWidth || innerWidth, newInnerHeight || innerHeight);
  }

  drawCurrentGuide = () => {
    const { currentIndex, maskList } = this.state;
    let target = maskList[currentIndex];
    if (target.transparentArea && target.transparentArea.x !== undefined) {
      let {x, y, width, height} = target.transparentArea;
      this.ctxDelegate('clearRect', x, y, width, height);
    }
    if (target.mouseOverId) { //有需要mouseOver 的 高亮内容
      this.triggerANode(target.elementId, true); //把hover内容弄出来
      setTimeout(()=>{
        let hoverTransparent = this.getElPosition(document.getElementById(target.mouseOverId))
        let {x, y, width, height} = hoverTransparent;
        if (target.mouseOverId !== 'help-content-guide-id') {
          this.ctxDelegate('clearRect', x, y-5, width, height+5);
        } else {
          this.ctxDelegate('clearRect', x-20, y-29, width + 40, height+58);
        }
      },200)
    }
  }

  componentWillMount() {
    EventUtils.addHandler(window, 'resize', this.resizeInit)
  }

  resizeInit = () => {
    this.props.onResize()
  }

  componentDidMount() {
    this.initGuideList();
    this.initMask();
  }

  componentWillUnmount() {
    const { animateIn, animateOut } = this.props;
    let content = this.container.children[0];
    content.className = content.className.replace(animateIn, animateOut);
    EventUtils.removeHandler(window, 'resize', this.resizeInit)
    setTimeout(() => {
      ReactDOM.unmountComponentAtNode(this.container);
      document.body.removeChild(this.container);
    }, 300);
  }

  componentWillReceiveProps(nextProps) {
    this.renderChildren(nextProps)
  }

  onNext = (index) => {
    const { innerWidth, innerHeight } = this.state;
    this.triggerANode('help-icon-popover-guide-id', false);
    this.triggerANode('user-info-dropdown-guide-id', false);
    this.ctxDelegate('clearRect', 0, 0, innerWidth, innerHeight);
    this.drawBackground();
    this.setState({currentIndex: index}, ()=>{
      this.drawCurrentGuide();
    })
  }

  renderChildren = props => {

    const {innerWidth, innerHeight, maskList} = this.state;
    const { className, animateIn } = props;
    ReactDOM.unstable_renderSubtreeIntoContainer(
      this,
      <div
        className={`mask-guide-canvas ${window.ISIE9 ? '' : ('animated ' + animateIn)} ${className}`}
      >
        <canvas id='mask-guide-canvas'
                width={innerWidth * window.devicePixelRatio}
                height={innerHeight * window.devicePixelRatio}
                style={{ height: innerHeight + 'px', width: innerWidth + 'px' }}
        />
        <SingleMainGuide
          RefreshList={()=>{this.resizeInit()}}
          actions={maskList}
          onNext={this.onNext}
          onClose={this.props.onClose}
        />
      </div>,
      this.container
    );
  };

  render() {
    return null;
  }

}

function mapStateToProps (state) {
  return {
    loginUser: state.login.loginUser,
    menuTree: state.login.menuTree,
  };
}

MaskGuide.propTypes = {
  className: React.PropTypes.string,
  style: React.PropTypes.object,
  animateIn: React.PropTypes.string,
  animateOut: React.PropTypes.string,
  hasMask: React.PropTypes.bool
};

MaskGuide.defaultProps = {
  className : '',
  style: {},
  animateIn: 'fadeIn',
  animateOut: 'fadeOut',
  hasMask: true
};

export default connect(mapStateToProps)(MaskGuide)
